﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.TextUtils;
using System;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;

namespace CatUtilsDll.Utils.Currency.WebUtils
{
    public partial class WebHelper
    {
        /// <summary>
        /// 检查连接是否是Url 不显示日志
        /// </summary>
        /// <param name="Link">需要检查的链接</param>
        /// <returns></returns>
        public static bool CheckIsUrl(string Link)
        {
            return CheckIsUrl(Link, false);
        }

        /// <summary>
        /// 检查连接是否是Url
        /// </summary>
        /// <param name="Link"></param>
        /// <param name="ShowLog">是否显示并且记录日志</param>
        /// <returns></returns>
        public static bool CheckIsUrl(string Link, bool ShowLog)
        {
            try
            {
                Uri host = new Uri(Link);

                return true;
            }
            catch (Exception ex)
            {
                if (ShowLog)
                {
                    Console.WriteLine($"检查内容：{Link}。不是链接。");
                    PrintLog.Log(ex);
                }
            }
            return false;
        }

        /// <summary>
        /// Url编码 默认UTF8
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string UrlEncode(string Url)
        {
            return UrlEncode(Url, Encoding.UTF8);
        }

        /// <summary>
        /// Url编码
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="encoding">自行设定编码格式</param>
        /// <returns></returns>
        public static string UrlEncode(string Url, Encoding encoding)
        {
            return System.Web.HttpUtility.UrlEncode(Url, encoding);
        }

        /// <summary>
        ///UrlEncode 编码
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        [Obsolete]
        public string UrlEncodeToUtf8(string Url)
        {
            return UrlEncode(Url);
        }

        /// <summary>
        /// Url解密
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string UrlDeCode(string Url)
        {
            return UrlDeCode(Url, Encoding.UTF8);
        }

        /// <summary>
        /// Url解密  自行设定解密模式
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string UrlDeCode(string Url, Encoding encoding)
        {
            return System.Web.HttpUtility.UrlDecode(Url, encoding);
        }

        /// <summary>
        /// 分析 url 字符串中的参数信息  没找到返回空字符串
        /// </summary>
        /// <param name="ParametersLink">需要解析的链接</param>
        /// <param name="KeyName">需要解析的链接</param>
        ///<param name="UrlDecode">是否对链接参数解码还原。True还原，Flase保持原样</param>
        /// <returns>获取链接参数，找到返回结果，没找到返回空。</returns>
        public static string GetLinkParameters(string ParametersLink, string KeyName, bool UrlDecode)
        {
            NameValueCollection nameValue = GetLinkParameters(ParametersLink, UrlDecode);
            if (nameValue[KeyName] == null)
                return "";
            return nameValue[KeyName];
        }

        /// <summary>
        /// 获取域名的顶级域名，不包含端口，需要端口直接用new Url("").host
        /// </summary>
        /// <param name="domain"></param>
        /// <returns></returns>
        public static string GetTopDomainName(string domain)
        {
            //https://www.safsd.asdfasdf.baidu.com.cn/ssssd/s/b/d/hhh.html?domain=sfsdf.com.cn&id=1
            domain = domain.Trim().ToLower();
            domain = TextHelper.ReplaceTextEnhance(domain, ":[0-9]{1,7}", "");
            string rootDomain = ".com.cn|.gov.cn|.cn|.com|.net|.org|.so|.co|.mobi|.tel|.biz|.info|.name|.me|.cc|.tv|.asiz|.hk";
            if (domain.StartsWith("http://")) domain = domain.Replace("http://", "");
            if (domain.StartsWith("https://")) domain = domain.Replace("https://", "");
            if (domain.StartsWith("www.")) domain = domain.Replace("www.", "");
            //safsd.asdfasdf.baidu.com.cn/ssssd/s/b/d/hhh.html?domain=sfsdf.com.cn&id=1
            if (domain.IndexOf("/") > 0)
                domain = domain.Substring(0, domain.IndexOf("/"));
            //safsd.asdfasdf.baidu.com.cn
            foreach (string item in rootDomain.Split('|'))
            {
                if (domain.EndsWith(item))
                {
                    domain = domain.Replace(item, "");
                    if (domain.LastIndexOf(".") > 0)//adfasd.asdfas.cn
                    {
                        domain = domain.Replace(domain.Substring(0, domain.LastIndexOf(".") + 1), "");
                    }
                    return domain + item;
                }
                continue;
            }
            return "";
        }

        /// <summary>
        /// 分析 url 字符串中的参数信息  使用方法：NameValueCollection["keyName"]
        /// </summary>
        /// <param name="ParametersLink">需要解析的链接</param>
        ///<param name="UrlDecode">是否对链接参数解码还原。True还原，Flase保持原样</param>
        /// <returns>返回键值对 使用方法：NameValueCollection["keyName"] </returns>
        public static NameValueCollection GetLinkParameters(string ParametersLink, bool UrlDecode)
        {
            NameValueCollection nvc = new NameValueCollection();
            int questionMarkIndex = ParametersLink.IndexOf('?');
            if (ParametersLink == null || questionMarkIndex == -1
                || questionMarkIndex == ParametersLink.Length - 1)
            { return nvc; }
            string ps = ParametersLink.Substring(questionMarkIndex + 1);
            // 开始分析参数对
            try
            {
                Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled);
                MatchCollection mc = re.Matches(ps);
                foreach (Match m in mc)
                {
                    string TempParameter = m.Result("$3");
                    if (UrlDecode)
                    {
                        TempParameter = UrlDeCode(m.Result("$3"));
                    }
                    nvc.Add(m.Result("$2"), TempParameter);
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }

            return nvc;
        }
    }
}